package cn.open.feishu.alert.common;

import cn.open.feishu.alert.common.utils.NumberUtil;
import cn.open.feishu.alert.config.FeiShuProperties;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.Data;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.PostConstruct;
import java.util.concurrent.*;
import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;

/**
 * @Description 记录保存异步线程
 * @Author fandy.lin
 * @Date 2021/8/30 2:54 下午
 **/
@Slf4j
@Data
public class SendAsyncExecutor implements Executor {
    private ExecutorService executors;
    private FeiShuProperties properties;

    public SendAsyncExecutor(FeiShuProperties properties) {
        this.properties = properties;
    }

    @PostConstruct
    public void init() {
        if (!NumberUtil.isGreatThanZero(properties.getCorePoolSize())) {
            properties.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        }
        if (!NumberUtil.isGreatThanZero(properties.getMaxPoolSize())) {
            properties.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2);
        }
        String poolName = "feishu-alert-pool-%d";
        ThreadFactory threadFactory = (new ThreadFactoryBuilder()).setNameFormat(poolName).build();
        this.executors = new ThreadPoolExecutor(properties.getCorePoolSize(), properties.getMaxPoolSize(), 3000L, TimeUnit.MILLISECONDS
                , new LinkedBlockingQueue(1024), threadFactory, new AbortPolicy());
        log.info("feishu slert async executor,corePoolSize:{},maxPoolSize{},threadNameFormat:{}", new Object[]{properties.getCorePoolSize(), properties.getMaxPoolSize(), poolName});
    }

    /**
     * 使用wapper传参给子线程绑定链路id
     *
     * @param command
     */
    @Override
    public void execute(@NonNull Runnable command) {
        if (command == null) {
            throw new NullPointerException("feishu alert async executor:command is marked non-null but is null");
        } else {
            this.executors.execute(command);
        }
    }
}